'use strict';

/*var app = angular.module('app');*/
angular.module('app').controller('bgMemberController', [ '$rootScope', '$scope', '$http', '$state','toaster','$modal',
	                                function($rootScope, $scope, $http, $state,toaster,$modal) {
		$scope.title = '人员管理';
        $scope.param = { };
        $scope.loading = false;
        
		$scope.search = function () {
	        $scope.loading = true;
			if($scope.param.IDCardNo==''){
			    $scope.param.IDCardNo=null;
			}
			if($scope.param.personName==''){
			    $scope.param.personName=null;
			}
	        if($scope.pageFlag != 1){//未点击翻页
			  	   $scope.param.pageNum=1;//将页码设置为1，即跳转回第一页
			  	}else{//点击翻页
			  	   $scope.pageFlag = 2;//将开关值设置为2
			  	}
			$.ajax({
				type: 'PUT',
	            dataType: 'json',
				contentType:'application/json;charset=UTF-8',
				url : 'dac/userManager/list',
				data: angular.toJson($scope.param)
			}).then(function(result) {
				console.log(result);
		        $scope.loading = false;
				if (result.httpCode == 200) {
					$scope.pageInfo = result;
					
				} else {
					$scope.msg = result.msg;
				}
				$scope.$apply();
				var userId = localStorage.getItem('userId');
				var strIds = getCookie(userId+"2");
				if(strIds===null){
					return;
				}
				var ids = strIds.split(",");
				for(var i=0;i<ids.length;i++){
					var id = ids[i];
					var object = document.getElementById(id);
					if(object!=null){
						object.checked = true;
					}
				}
				var checkBoxs = $(".tbody input[name='Fruit']").length;//单选框的个数
                var checkeds = $(".tbody input[name='Fruit']:checked").length//单选框选中的个数
                var checkBoxss = $(".tbody input[name='Fruit']");
                $("#allCheck").prop("checked",checkBoxs === checkeds ? true : false);//个数与选中个数相同时，全选按钮选中，否则不选中
			});
		}
		
		

		//从本地获取localstorage数据，对权限按钮做隐藏
		var personAuth =localStorage.getItem("PersonAuth");//获取PersonAuth的值
		console.log(personAuth);
		personAuth = personAuth.split(',');
		for(var i = 0;i<personAuth.length;i++){
			if(personAuth[i]=='main.member.read'){
				$scope.read = true;
			}
			if(personAuth[i]=='main.member.add'){
				$scope.add = true;
			}
			if(personAuth[i]=='main.member.update'){
				$scope.update = true;
			}
			if(personAuth[i]=='main.member.delete'){
				$scope.dele = true;
			}
		}
		
		    //全选按钮
            $scope.allCheck = function($event){
                var allcheck = $event.target ;//全选按钮
                var checked = allcheck.checked ;//选中状态
                var checkBoxs = $(".tbody input[name='Fruit']");
                checkBoxs.each(function(i){
                    this.checked = checked;
                    $scope.saveIdOrRemoveId(this);
                });
            }
            
            //存储被勾选中的id或者删除取消勾选的id
			$scope.saveIdOrRemoveId = function(check){
				var userId = localStorage.getItem('userId');
				var OldIds = getCookie(userId+"2");
				if(OldIds===null){
					OldIds = "";
				}
				var checked = check.checked ; //当前行勾选按钮的状态
				if(checked){
					OldIds +=  check.value+",";
					setCookie(userId+"2",OldIds,'h1');
					return;
					}
				var strs= new Array(); //定义一数组 
				strs=OldIds.split(","); //字符分割
				var newIds = "";
				for(var i=0;i<strs.length;i++){
					if(strs[i]===check.value||strs[i]===""){
						setCookie(userId+"2",newIds,'h1');
						continue;
					}
					newIds += strs[i]+",";
					setCookie(userId+"2",newIds,'h1');
				}
				
			}
            

 			//检测没有全选就将全选按钮变为未选状态
            $scope.checkStatus = function () {
                var checkBoxs = $(".tbody input[name='Fruit']").length;//单选框的个数
                var checkeds = $(".tbody input[name='Fruit']:checked").length//单选框选中的个数
                var checkBoxss = $(".tbody input[name='Fruit']");
                checkBoxss.each(function(i){
                    $scope.saveIdOrRemoveId(this);
                });
                $("#allCheck").prop("checked",checkBoxs === checkeds ? true : false);//个数与选中个数相同时，全选按钮选中，否则不选中
            }


		$scope.search();
		$scope.clearSearch = function() {
			$scope.search();
		}
		
		$scope.disableItem = function(id, enable) {
			
		}
		
		$scope.delAll = function(){
			var userId = localStorage.getItem('userId');
				var ids = getCookie(userId+"2");
				delCookies(userId+"2");
		  var checkeds = ids.split(",")//单选框选中的个数
		       delCookies(userId);
                if(checkeds.length === 1 ){
                alert('最小选中一个');
                return;
                }
                $scope.delItem(ids);
		}
 		
		$scope.delItem = function(id) {
		 	  
			  if (confirm("确认删除吗？")==true)
			    {
				  $.ajax({
						type: 'DELETE',
			            dataType: 'json',
						contentType:'application/json;charset=UTF-8',
						url : 'dac/userManager/delete',
						data: angular.toJson({'personId': id})
					}).then(function(result) {
						if (result.httpCode == 200) {
							 	toaster.clear('*');
			                    toaster.pop('success', '', "删除成功");
							$scope.search();
						} 
						else 
						{
							 toaster.clear('*');
							 toaster.pop('false', '', result.msg);
						}
						$scope.$apply();
					});
			    }
			  else
			    {
				  $state.go('main.member.list');
			    };
			
			
			
		};
		
		
		
	    $scope.openDevice = function(id) {
	    	alert(id);
	           var modalInstance = $modal.open({
	               templateUrl : 'delete.html',//script标签中定义的id
	               controller : 'deleteModalCtrl',//modal对应的Controller
	               size: 'lg'
	           });
	           
	           $scope.ok = function () { 
	        	   $.ajax({
	   				type: 'DELETE',
	   	            dataType: 'json',
	   				contentType:'application/json;charset=UTF-8',
//	   				url : 'dac/userManager/delete',
	   				url : '#',
	   				data: angular.toJson({'personId': id})
	   			}).then(function(result) {
	   				if (result.httpCode == 200) {
	   					alert("删除成功");
	   					$scope.search();
	   				} else {
	   					alert("删除失败");
	   				}
	        	   
	           });
	           
	           $scope.cancel = function () {    
	        	   $modalInstance.dismiss('cancel');  
	           };

	       }
	    }
		
		// 翻页
        $scope.pagination = function (page) {
            $scope.param.pageNum=page;
            $scope.pageFlag = 1;//将开关值设置为1
            $scope.search();
        };
        
        //读取cookies
           function getCookie(name){
           	  var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
				if(arr=document.cookie.match(reg))
				return unescape(arr[2]);
				else
				return null;
           }
           
           //删除cookies
           function delCookies(name){
           	 var exp = new Date();
			 exp.setTime(exp.getTime() - 1);
				var cval=getCookie(name);
				if(cval!=null)
			document.cookie= name + "="+cval+";expires="+exp.toGMTString();
           }
            
            //设置cookies
			//如果需要设定自定义过期时间
			//那么把上面的setCookie　函数换成下面两个函数就ok;
			//程序代码
			function setCookie(name,value,time)
			{
			var strsec = getsec(time);
			var exp = new Date();
			exp.setTime(exp.getTime() + strsec*1);
			document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
			}
			function getsec(str)
			{
			var str1=str.substring(1,str.length)*1;
			var str2=str.substring(0,1);
			if (str2=="s")
			{
			return str1*1000;
			}
			else if (str2=="h")
			{
			return str1*60*60*1000;
			}
			else if (str2=="d")
			{
			return str1*24*60*60*1000;
			}
			}
			//这是有设定过期时间的使用示例：
			//s20是代表20秒
			//h是指小时，如12小时则是：h12
			//d是天数，30天则：d30
} ]);


app.controller('deleteModalCtrl', function($scope, $rootScope, $modal,$modalInstance,items) {
	
    $scope.param = { };
	$scope.search = function () {
        $scope.loading = true;
		$.ajax({
			type: 'POST',
            dataType: 'json',
			contentType:'application/json;charset=UTF-8',
			url : '/dac/bm/house/list',
			data: angular.toJson($scope.param)
		}).then(function(result) {
	        $scope.loading = false;
			if (result.httpCode == 200) {
				
			} else {
				$scope.msg = result.msg;
			}
			$scope.$apply();
		});
	}
	 
    $scope.cancel = function() {  
        $modalInstance.dismiss('cancel');  
    }; 

});
